import React, {Component} from 'react';
import {connect, history} from 'umi';
import {message, Tag} from 'antd';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
import NoticeIcon from '../NoticeIcon';
import styles from './index.less';
import {getNotice, sendMessageToClient} from "@/services/home";

class GlobalHeaderRight extends Component {
  constructor() {
    super();
    this.state = {
      notice: []
    }
  }


  componentDidMount() {
    const {dispatch} = this.props;
    //this.getNotice();

    if (dispatch) {
      dispatch({
        type: 'global/fetchNotices',
      });
    }

    this.websocketInit();
  }

  websocketInit = () => {
    // 根据http协议判断是否为ws或wss
    const proto = document.location.protocol === 'http:' ? 'ws:' : 'wss:';
    // 取地址+端口，配置80端口时port是空的，所以判断一下
    const address = document.location.port ? `${document.location.hostname}:${document.location.port}` : document.location.hostname;
    // 拼接请求地址
    const wsuri = `${proto}//${address}/wsmanage/ws`;

    if (typeof (WebSocket) === 'undefined') {
      console.log('您的浏览器不支持socket');
    } else {
      // 实例化socket
      this.socket = new WebSocket(wsuri);
      // 监听socket连接
      this.socket.onopen = this.websocketOnOpen;
      // 监听socket错误信息
      this.socket.onerror = this.websocketOnError;
      // 监听socket消息
      this.socket.onmessage = this.websocketOnMessage;
      this.socket.onclose = this.websocketClose;
    }
  }

  websocketOnOpen = () => { // 连接建立之后执行send方法发送数据
    console.log('onOpen');
    this.websocketSend(`userId:${JSON.parse(sessionStorage.getItem('user')).sysUser.userId}`)
  }

  websocketOnError = () => {// 连接建立失败重连
    console.log('onError');
  }

  websocketOnMessage = (e) => { // 数据接收
    console.log('onMessage');
    const socketMessage = JSON.parse(e.data)
    if (socketMessage.type === 2) { // 如果是待办数据，则继续
      const {dispatch} = this.props;

      if (dispatch) {
        dispatch({
          type: 'global/changePortalStatus',
          payload: true,
        });
      }
      return;
    }
    const notice = socketMessage.data.map(item => {
      const start = moment(item.createTime)
      const end = moment();
      const day = end.diff(start, 'days');
      const hour = end.diff(start, 'hours');
      const min = end.diff(start, 'minutes');
      let extra = '';
      if (day === 0) {
        if (hour === 0) {
          extra = min + '分钟前'
          item.status = 'todo'
        } else {
          extra = hour + '小时前'
          item.status = 'processing'
        }
      } else {
        extra = day + '天前'
        item.status = 'urgent'
      }
      item.extra = extra;
      return item
    })
    this.setState({
      notice: notice
    })
  }

  websocketSend = (Data) => { // 数据发送
    this.socket.send(Data);
  }

  websocketClose = (e) => {  // 关闭
    console.log('断开连接', e);
  }

  getNotice = () => {
    getNotice().then(res => {
      if (res && res.status === '0') {
        res.data = res.data.map(item => {
          const start = moment(item.createTime, 'YYYY-MM-DD HH:mm:ss')
          const end = moment();
          const day = end.diff(start, 'days');
          const hour = end.diff(start, 'hours');
          const min = end.diff(start, 'minutes');
          let extra = '';
          if (day === 0) {
            if (hour === 0) {
              extra = min + '分钟前'
              item.status = 'todo'
            } else {
              extra = hour + '小时前'
              item.status = 'processing'
            }
          } else {
            extra = day + '天前'
            item.status = 'urgent'
          }
          item.extra = extra;
          return item
        })
        this.setState({
          notice: res.data
        })
      }
    })
  }


  changeReadState = (clickedItem) => {
    const {id} = clickedItem;
    const {dispatch} = this.props;

    if (dispatch) {
      dispatch({
        type: 'global/changeNoticeReadState',
        payload: id,
      });
    }
  };

  goToPage = (item) => {
    switch (item.title) {
      case '采购待审批':
        history.replace('/purchase/purchase-approval');
        break;
      case '订单待审批':
        history.replace('/order/order-approval');
        break;
      case '工艺在途':
        history.replace('/processing/processing-manage');
        break;
      default:
        break;
    }
  };

  handleNoticeClear = (title, key) => {
    const {dispatch} = this.props;
    message.success(`${'清空了'} ${title}`);

    if (dispatch) {
      dispatch({
        type: 'global/clearNotices',
        payload: key,
      });
    }
  };

  getNoticeData = () => {
    // const { notices = [] } = this.props;

    const notices = this.state.notice

    if (!notices || notices.length === 0 || !Array.isArray(notices)) {
      return {};
    }

    const newNotices = notices.map((notice) => {
      const newNotice = {...notice};

      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }

      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }

      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: 'green',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag
            color={color}
            style={{
              marginRight: 0,
            }}
          >
            {newNotice.extra}
          </Tag>
        );
      }

      return newNotice;
    });
    return groupBy(newNotices, 'type');
  };
  getUnreadData = (noticeData) => {
    const unreadMsg = {};
    Object.keys(noticeData).forEach((key) => {
      const value = noticeData[key];

      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }

      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter((item) => !item.read).length;
      }
    });
    return unreadMsg;
  };

  render() {
    const {currentUser, fetchingNotices, onNoticeVisibleChange} = this.props;
    const {notice} = this.state;
    const noticeData = this.getNoticeData();
    const unreadMsg = this.getUnreadData(noticeData);
    return (
      <NoticeIcon
        className={styles.action}
        count={notice ? notice.length : null}
        onItemClick={(item) => {
          this.goToPage(item);
        }}
        loading={fetchingNotices}
        clearText="清空"
        viewMoreText="查看更多"
        onClear={this.handleNoticeClear}
        onPopupVisibleChange={onNoticeVisibleChange}
        onViewMore={() => message.info('Click on view more')}
        clearClose
      >
        {/*<NoticeIcon.Tab*/}
        {/*  tabKey="notification"*/}
        {/*  count={unreadMsg.notification}*/}
        {/*  list={noticeData.notification}*/}
        {/*  title="通知"*/}
        {/*  emptyText="你已查看所有通知"*/}
        {/*  showViewMore*/}
        {/*/>*/}
        {/*<NoticeIcon.Tab*/}
        {/*  tabKey="message"*/}
        {/*  count={unreadMsg.message}*/}
        {/*  list={noticeData.message}*/}
        {/*  title="消息"*/}
        {/*  emptyText="您已读完所有消息"*/}
        {/*  showViewMore*/}
        {/*/>*/}
        <NoticeIcon.Tab
          tabKey="event"
          title="待办"
          emptyText="你已完成所有待办"
          count={unreadMsg.event}
          list={noticeData.event}
          showViewMore
        />
      </NoticeIcon>
    );
  }
}

export default connect(({user, global, loading}) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingMoreNotices: loading.effects['global/fetchMoreNotices'],
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
}))(GlobalHeaderRight);
